#!/bin/bash

# Build script for cpp_learn_template_srsj project

set -e  # Exit on any error

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Function to print colored output
print_status() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Default values
BUILD_TYPE="Debug"
BUILD_DIR="build"
CLEAN=false
VERBOSE=false

# Parse command line arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        -r|--release)
            BUILD_TYPE="Release"
            shift
            ;;
        -d|--debug)
            BUILD_TYPE="Debug"
            shift
            ;;
        -c|--clean)
            CLEAN=true
            shift
            ;;
        -v|--verbose)
            VERBOSE=true
            shift
            ;;
        -h|--help)
            echo "Usage: $0 [OPTIONS]"
            echo "Options:"
            echo "  -r, --release    Build in Release mode (default: Debug)"
            echo "  -d, --debug      Build in Debug mode"
            echo "  -c, --clean      Clean build directory before building"
            echo "  -v, --verbose    Verbose build output"
            echo "  -h, --help       Show this help message"
            exit 0
            ;;
        *)
            print_error "Unknown option: $1"
            echo "Use -h or --help for usage information"
            exit 1
            ;;
    esac
done

print_status "Building cpp_learn_template_srsj project"
print_status "Build type: $BUILD_TYPE"

# Clean build directory if requested
if [ "$CLEAN" = true ]; then
    print_status "Cleaning build directory..."
    rm -rf "$BUILD_DIR"
fi

# Create build directory
mkdir -p "$BUILD_DIR"
cd "$BUILD_DIR"

# Configure with CMake
print_status "Configuring project with CMake..."
CMAKE_ARGS="-DCMAKE_BUILD_TYPE=$BUILD_TYPE"

if [ "$VERBOSE" = true ]; then
    CMAKE_ARGS="$CMAKE_ARGS -DCMAKE_VERBOSE_MAKEFILE=ON"
fi

cmake .. $CMAKE_ARGS

# Build the project
print_status "Building project..."
if [ "$VERBOSE" = true ]; then
    make VERBOSE=1
else
    make -j$(nproc)
fi

print_success "Build completed successfully!"

# Show available executables
print_status "Available executables:"
find . -type f -executable -not -path "*/CMakeFiles/*" -not -name "cmake*" -not -name "*.sh" | sort

print_status "Build artifacts are in the '$BUILD_DIR' directory"
print_status "You can run individual executables or use the custom targets:"
echo "  - make run_test_initialization"
echo "  - make run_all_templates"
echo "  - make run_testCode_main"
echo "  - make run_testCode_no_modules"
echo "  - make boost_examples"
